﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;


    public class FSM
    {
        public delegate void OnEnter();
        public delegate void OnExit();
        public delegate void OnFixUpdate();
        public class State
        {
            public OnEnter OnEnter;
            public OnExit OnExit;
            public OnFixUpdate OnFixUpdate;
            public OnFixUpdate OnUpdate;

            public string Name {get;set;}

            public State(string name) {
                Name = name;
            }
            public Dictionary <string, Tran> TranDic = new Dictionary<string, Tran>();

            public void DoFixUpdate() {
                if (OnFixUpdate != null) {
                    OnFixUpdate();
                }
            }
            public void DoUpdate() {
                if (OnUpdate != null) {
                    OnUpdate();
                }
            }
        }

        public class Tran
        {
            public string Name {get;set;}
            public State fromState;
            public State toState;
            public Tran(State from, State to, string tranName) {
                fromState = from;
                toState = to;
                Name = tranName;
            }
        }

        public State currState;

        Dictionary <string, State> StateDic = new Dictionary<string, State>();
        public State GetState(string name) {
            return StateDic[name];
        }
        public void AddState(State state)
        {
            StateDic[state.Name] = state;
        }

        public void AddTranslation(Tran tran)
        {
            tran.fromState.TranDic[tran.Name] = tran;
        }

        public void Start(State defaultState) {
            currState = defaultState;
            Debug.Log(currState.Name);
            if (currState.OnEnter != null)
                currState.OnEnter();
        }

        public void HandleEvent(string name)
        {
            if (currState != null && currState.TranDic.ContainsKey(name)) {
                Debug.Log("退出"+currState.Name);
                if (currState.OnExit != null)
                    currState.OnExit();
                currState = currState.TranDic[name].toState;
                Debug.Log("进入"+currState.Name);
                if (currState.OnEnter != null)
                    currState.OnEnter();
            }
        }


    }

    

